import React, { useState, useRef } from "react";
import "./personalized.scss";
import { Image, Popup, Button } from "antd-mobile";
import img1 from "../../../../assets/personalized.png";
import { useNavigate } from "react-router-dom";
interface IndexProps {}
const Index: React.FC<IndexProps> = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedImageSrc, setSelectedImageSrc] = useState<string | null>(null); // 保存选择的图片
  const navigate = useNavigate();
  const fileInputRef = useRef<HTMLInputElement>(null); // useRef用于引用input元素

  const handelToMyD = () => {
    navigate("/myD");
  };

  const handleImageClick = () => {
    setModalVisible(true);
  };

  const handleCloseModal = () => {
    setModalVisible(false);
  };

  const handleTakePhoto = () => {
    alert("跳转到拍照页面"); // 实际情况下需要实现拍照逻辑
    setModalVisible(false);
  };

  const handleChooseFromAlbum = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files && event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setSelectedImageSrc(reader.result as string); // 将选择的图片保存到状态中
      };
      reader.readAsDataURL(file);
    }
    setModalVisible(false); // 关闭弹出层
  };
  return (
    <div>
      <p>为您设置一张照片吧!</p>
      <div className="conImg" onClick={handleImageClick}>
        <Image
          src={selectedImageSrc || img1} // 如果有选择的图片，则显示选择的图片，否则显示默认图片
          fit="cover"
          style={{ borderRadius: 4 }}
        />
      </div>
      {/* 底部弹出的选择框 */}
      <Popup
        visible={modalVisible}
        onClose={handleCloseModal}
        closeOnMaskClick={true}
      >
        <div style={{ padding: "16px" }}>
          <Button onClick={handleTakePhoto}>拍一张</Button>
          <Button onClick={handleChooseFromAlbum}>从相册选择</Button>
        </div>
      </Popup>
      {/* 隐藏的文件选择器 */}
      <input
        type="file"
        ref={fileInputRef}
        accept="image/*"
        style={{ display: "none" }}
        onChange={handleFileChange}
      />
      <button onClick={handelToMyD}>完成设置</button>
    </div>
  );
};

export default Index;
